package com.comac.print.component.app.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.comac.mom.simpleintegration.oss.OssUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author yinhaoye
 * @version 1.0
 * @date 2023/8/14 17:03
 * @description
 */
public class OssUtilPlus{

    private static final Logger log = LoggerFactory.getLogger(OssUtil.class);
    private static String PATH = "/mom-file-service-app/file/getFile";
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private OSS ossClient;
    private static final String separator = "/";
    private static final String spot = ".";
    private static final String http = "http://";
    private static final String https = "https://";

    public static OssUtilPlus create(String endpoint, String accessKeyId, String accessKeySecret, String bucketName) throws Exception {
        if (StringUtils.isBlank(endpoint)) {
            throw new Exception("Endpoint is not null!");
        } else if (StringUtils.isBlank(accessKeyId)) {
            throw new Exception("AccessKeyId is not null!");
        } else if (StringUtils.isBlank(accessKeySecret)) {
            throw new Exception("AccessKeySecret is not null!");
        } else if (StringUtils.isBlank(bucketName)) {
            throw new Exception("BucketName is not null!");
        } else {
            return new OssUtilPlus(endpoint, accessKeyId, accessKeySecret, bucketName);
        }
    }

    private OssUtilPlus(String endpoint, String accessKeyId, String accessKeySecret, String bucketName) {
        this.endpoint = endpoint;
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.bucketName = bucketName;
        this.ossClient = this.init();
    }

    private OSS init() {
        return (new OSSClientBuilder()).build(this.endpoint, this.accessKeyId, this.accessKeySecret);
    }

    public JSONObject upload(String fileName, String dir, InputStream stream) throws Exception {
        return this.upload(fileName, dir, (String)null, (InputStream)stream);
    }

    public JSONObject upload(String fileName, String dir, InputStream stream, String pathUrl) throws Exception {
        return this.upload(fileName, dir, (String)null, stream, pathUrl);
    }

    public JSONObject uploadOss(String fileName, String dir, InputStream stream) throws Exception {
        return this.uploadByOss(fileName, dir, (String)null, stream);
    }

    public JSONObject upload(String fileName, String dir, String keyName, InputStream stream) throws Exception {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String serverName = request.getServerName();
        log.info("serverName : {}", serverName);
        String scheme = request.getScheme();
        log.info("scheme : {}", scheme);
        int port = request.getServerPort();
        log.info("port : {}", port);
        if (StringUtils.isBlank(fileName)) {
            throw new Exception("FileName is not null!");
        } else {
            if (StringUtils.isBlank(dir)) {
                dir = "/";
            } else if (!dir.endsWith("/")) {
                dir = dir + "/";
            }

            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            String keyPath;
            if (StringUtils.isEmpty(keyName)) {
                keyPath = dir + UUID.randomUUID() + "." + fileType;
            } else {
                keyPath = dir + keyName;
            }

            String prefix;
            if (this.endpoint.startsWith("http://")) {
                prefix = "http://" + this.bucketName + "." + this.endpoint.substring("http://".length());
            } else if (this.endpoint.startsWith("https://")) {
                prefix = "https://" + this.bucketName + "." + this.endpoint.substring("https://".length());
            } else {
                prefix = "http://" + this.bucketName + "." + this.endpoint;
            }

            PutObjectResult putObjectResult = this.upload(fileName, stream, keyPath);
            String eTag = putObjectResult.getETag();
            StringBuffer bf = new StringBuffer(scheme);
            bf.append("://").append(serverName).append(":").append(port).append(PATH).append("?ossUrl=").append(prefix).append("/").append(keyPath);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("printSheetOssUrl", bf.toString());
            jsonObject.put("md5Code", eTag);
            return jsonObject;
        }
    }

    public JSONObject upload(String fileName, String dir, String keyName, InputStream stream, String pathUrl) throws Exception {
        if (StringUtils.isBlank(fileName)) {
            throw new Exception("FileName is not null!");
        } else {
            if (StringUtils.isBlank(dir)) {
                dir = "/";
            } else if (!dir.endsWith("/")) {
                dir = dir + "/";
            }

            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            String keyPath;
            if (StringUtils.isEmpty(keyName)) {
                keyPath = dir + UUID.randomUUID() + "." + fileType;
            } else {
                keyPath = dir + keyName;
            }

            String prefix;
            if (this.endpoint.startsWith("http://")) {
                prefix = "http://" + this.bucketName + "." + this.endpoint.substring("http://".length());
            } else if (this.endpoint.startsWith("https://")) {
                prefix = "https://" + this.bucketName + "." + this.endpoint.substring("https://".length());
            } else {
                prefix = "http://" + this.bucketName + "." + this.endpoint;
            }

            PutObjectResult putObjectResult = this.upload(fileName, stream, keyPath);
            String eTag = putObjectResult.getETag();
            StringBuffer bf = new StringBuffer(pathUrl);
            bf.append(prefix).append("/").append(keyPath);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("printSheetOssUrl", bf.toString());
            jsonObject.put("md5Code", eTag);
            return jsonObject;
        }
    }

    public JSONObject uploadByOss(String fileName, String dir, String keyName, InputStream stream) throws Exception {
        if (StringUtils.isBlank(fileName)) {
            throw new Exception("FileName is not null!");
        } else {
            if (StringUtils.isBlank(dir)) {
                dir = "/";
            } else if (!dir.endsWith("/")) {
                dir = dir + "/";
            }

            String keyPath;
            if (StringUtils.isEmpty(keyName)) {
                keyPath = dir + UUID.randomUUID();
            } else {
                keyPath = dir + keyName;
            }

            String prefix;
            if (this.endpoint.startsWith("http://")) {
                prefix = "http://" + this.bucketName + "." + this.endpoint.substring("http://".length());
            } else if (this.endpoint.startsWith("https://")) {
                prefix = "https://" + this.bucketName + "." + this.endpoint.substring("https://".length());
            } else {
                prefix = "http://" + this.bucketName + "." + this.endpoint;
            }

            PutObjectResult putObjectResult = this.upload(fileName, stream, keyPath);
            String url = prefix + "/" + keyPath;
            String eTag = putObjectResult.getETag();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("printSheetOssUrl", url);
            jsonObject.put("md5Code", eTag);
            return jsonObject;
        }
    }

    private PutObjectResult upload(String fileName, InputStream stream, String keyPath) throws IOException {
        PutObjectRequest putObjectRequest = new PutObjectRequest(this.bucketName, keyPath, stream);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength((long)stream.available());
        metadata.setCacheControl("no-cache");
        metadata.setHeader("Pragma", "no-cache");
        metadata.setContentEncoding("utf-8");
        metadata.setContentDisposition("attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        putObjectRequest.setMetadata(metadata);

        PutObjectResult putObjectResult = null;
        try {
            putObjectResult = this.ossClient.putObject(putObjectRequest);
        } catch (Throwable var10) {
            throw new OSSException("上传失败！filename = " + fileName, var10);
        } finally {
            this.ossClient.shutdown();
        }
        return putObjectResult;

    }

    public static void main(String[] args) throws Exception {
        String endpoint = "http://oss-cn-shanghai-internal.aliyuncs.com";
        String accessKeyId = "LTAI4FukcLcSxbhVLctWtbZy";
        String accessKeySecret = "lKONMAaWFDF0HtwBoM14DmEuUeAU7q";
        String bucketName = "comac-mom2-dev";
        String PATH = "MOM2/FO-EXECUTE";
        String content = "test";
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content.getBytes());
        OssUtilPlus ossUtil = create(endpoint, accessKeyId, accessKeySecret, bucketName);
        JSON url = ossUtil.upload("test.txt", PATH, (String)"1234567890.test", (InputStream)byteArrayInputStream);
        System.out.println(url);
    }

}
